package com.sale.salesystem.controller;

import com.sale.salesystem.dto.UserLoginDTO;
import com.sale.salesystem.dto.UserRegisterDTO;
import com.sale.salesystem.entity.SysUser;
import com.sale.salesystem.service.UserService;
import com.sale.salesystem.vo.ResultVO;
import com.sale.salesystem.vo.UserVO;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户相关接口
 */
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
@CrossOrigin
public class UserController {

    private final UserService userService;

    /**
     * 用户登录
     * 
     * @param loginDTO 登录信息
     * @return 用户信息和token
     * 
     *         示例请求：
     *         POST /api/user/login
     *         {
     *         "username": "admin",
     *         "password": "123456"
     *         }
     * 
     *         示例响应：
     *         {
     *         "code": 200,
     *         "message": "success",
     *         "data": {
     *         "id": 1,
     *         "username": "admin",
     *         "role": "ADMIN",
     *         "token": "xxx"
     *         }
     *         }
     */
    @PostMapping("/login")
    public ResultVO<UserVO> login(@Valid @RequestBody UserLoginDTO loginDTO) {
        return ResultVO.success(userService.login(loginDTO));
    }

    /**
     * 用户注册
     * 
     * @param registerDTO 注册信息
     * @return 用户信息和token
     * 
     *         示例请求：
     *         POST /api/user/register
     *         {
     *         "username": "zhangsan",
     *         "password": "123456",
     *         "confirmPassword": "123456"
     *         }
     * 
     *         示例响应：
     *         {
     *         "code": 200,
     *         "message": "success",
     *         "data": {
     *         "id": 2,
     *         "username": "zhangsan",
     *         "role": "VISITOR",
     *         "token": "xxx"
     *         }
     *         }
     */
    @PostMapping("/register")
    public ResultVO<UserVO> register(@Valid @RequestBody UserRegisterDTO registerDTO) {
        return ResultVO.success(userService.register(registerDTO));
    }

    /**
     * 获取当前登录用户信息
     * 
     * @return 用户信息
     * 
     *         示例请求：
     *         GET /api/user/info
     *         Header: {
     *         "Authorization": "Bearer xxx"
     *         }
     * 
     *         示例响应：
     *         {
     *         "code": 200,
     *         "message": "success",
     *         "data": {
     *         "id": 1,
     *         "username": "admin",
     *         "role": "ADMIN"
     *         }
     *         }
     */
    @GetMapping("/info")
    public ResultVO<UserVO> getUserInfo() {
        return ResultVO.success(userService.getCurrentUser());
    }

    @GetMapping("/search")
    public ResultVO<List<UserVO>> searchUsers(@RequestParam String username) {
        return ResultVO.success(userService.searchByUsername(username));
    }
}